package org.dlx.drpc.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.dlx.drpc.core.common.IRPCDecoder;

import java.nio.ByteBuffer;

public class JsonDecoder implements IRPCDecoder
{
    @Override
    public Object decode(byte[] msg) throws Exception
    {
        ByteBuffer bb = ByteBuffer.wrap(msg);
        TypeReference<?> tr = null;
        switch (bb.getInt()){
            case 1:
                tr = new TypeReference<ExpRequest>(){};
                break;
            case 2:
                tr = new TypeReference<ExpResponse>(){};
                break;
            default:
                throw new Exception("不支持的类型");
        }
        byte[] content = new byte[bb.remaining()];
        bb.get(content);
        return JSON.parseObject(new String(content, "UTF8"), tr);
    }
}
